const Sqlite = require("./sqlite.cjs");
const DATA = require("./Data.cjs");
const initTables = async (reset = false) => {
  const DB = new Sqlite();
  const tables = await DB.getTableNames();
  // console.log(tables);
  for (let tab of Object.values(DATA.tableNeeded)) {
    if (tables.includes(tab.tableName)) {
      // reset table for testing purpose
      if (reset) {
        try {
          await DB.deleteTable(tab.tableName);
          await DB.deleteTable(tab.tableName + "_data");
        } catch (e) {
          console.error(`warning: delteTable? table not find. ` + e);
        }
      } else {
        //
        console.log("tab exists. init...done");
        return;
      }
    }
    // 1.create table schemas
    await DB.createTable(tab.tableName);
    await DB.insertManyData(tab);
    // 2.create table data schemas
    await DB.createTable_data(tab);
    // 3.add user,admin,superadmin --add data if exists.
    if ("_data" in tab) {
      await DB.insertManyData(tab._data);
      const datas = await DB.queryTable(tab._data);
      console.log(datas);
    }
  }
  console.log("init...done");

  DB.close();
};
initTables(true);
//

module.exports = {
  initTables,
};
